<template>
  <div id="tagManagePage">
    <h2 style="margin-bottom: 16px">标签管理</h2>

    <!-- 搜索和添加 -->
    <div class="search-add-bar">
      <a-input-search
        v-model:value="searchText"
        placeholder="搜索标签"
        enter-button
        style="width: 300px"
        @search="fetchTagList"
      />
      <a-button type="primary" style="margin-left: 12px" @click="showAddModal = true">
        <plus-outlined /> 添加标签
      </a-button>
    </div>

    <!-- 标签列表 -->
    <a-table
      :columns="columns"
      :data-source="tagList"
      :loading="loading"
      row-key="id"
      :pagination="{
        pageSize: 10,
        current: currentPage,
        total: total,
        onChange: handlePageChange
      }"
    >
      <template #action="{ record }">
        <a-button size="small" @click="editTag(record)">编辑</a-button>
        <a-popconfirm
          title="确定要删除这个标签吗？"
          @confirm="deleteTag(record.id)"
          ok-text="确定"
          cancel-text="取消"
        >
          <a-button size="small" danger style="margin-left: 8px">删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>

    <!-- 添加/编辑标签弹窗 -->
    <a-modal
      v-model:open="showAddModal"
      :title="editingTag ? '编辑标签' : '添加标签'"
      @ok="handleAddOrEditTag"
      @cancel="handleCancel"
    >
      <a-form :model="tagForm" layout="vertical">
        <a-form-item
          label="标签名称"
          name="tagName"
          :rules="[{ required: true, message: '请输入标签名称' }]"
        >
          <a-input v-model:value="tagForm.tagName" placeholder="请输入标签名称" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            v-model:value="tagForm.description"
            placeholder="请输入标签描述"
            :auto-size="{ minRows: 2, maxRows: 5 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import {
  addTagUsingPost,
  updateTagUsingPost,
  deleteTagUsingPost,
  listTagByPageUsingPost
} from '@/api/tagController.ts'

// 数据
const tagList = ref<API.TagVO[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const searchText = ref('')

// 弹窗相关
const showAddModal = ref(false)
const editingTag = ref<API.TagVO | null>(null)
const tagForm = reactive<{
  tagName: string
  description: string
}>({ tagName: '', description: '' })

// 表格列配置
const columns = [
  {
    title: '标签名称',
    dataIndex: 'tagName',
    key: 'tagName',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
    slots: { customRender: 'action' },
  },
]

// 获取标签列表
const fetchTagList = async () => {
  loading.value = true
  try {
    const res = await listTagByPageUsingPost({
      current: currentPage.value,
      pageSize: 10,
      tagName: searchText.value
    })
    if (res.data.code === 0 && res.data.data) {
      tagList.value = res.data.data.records || []
      total.value = res.data.data.total || 0
    } else {
      message.error('获取标签列表失败')
    }
  } catch (error) {
    console.error('获取标签列表失败', error)
    message.error('获取标签列表失败')
  } finally {
    loading.value = false
  }
}

// 添加或编辑标签
const handleAddOrEditTag = async () => {
  if (!tagForm.tagName.trim()) {
    message.error('请输入标签名称')
    return
  }

  try {
    if (editingTag.value) {
      // 编辑标签
      const res = await updateTagUsingPost({
        id: editingTag.value.id,
        tagName: tagForm.tagName,
        description: tagForm.description
      })
      if (res.data.code === 0) {
        message.success('标签更新成功')
        fetchTagList()
        handleCancel()
      } else {
        message.error('标签更新失败')
      }
    } else {
      // 添加标签
      const res = await addTagUsingPost({
        tagName: tagForm.tagName,
        description: tagForm.description
      })
      if (res.data.code === 0) {
        message.success('标签添加成功')
        fetchTagList()
        handleCancel()
      } else {
        message.error('标签添加失败')
      }
    }
  } catch (error) {
    console.error('操作标签失败', error)
    message.error('操作标签失败')
  }
}

// 删除标签
const deleteTag = async (id: number) => {
  try {
    const res = await deleteTagUsingPost({ id })
    if (res.data.code === 0) {
      message.success('标签删除成功')
      fetchTagList()
    } else {
      message.error('标签删除失败')
    }
  } catch (error) {
    console.error('删除标签失败', error)
    message.error('删除标签失败')
  }
}

// 编辑标签
const editTag = (tag: API.TagVO) => {
  editingTag.value = tag
  tagForm.tagName = tag.tagName || ''
  tagForm.description = tag.description || ''
  showAddModal.value = true
}

// 取消操作
const handleCancel = () => {
  showAddModal.value = false
  editingTag.value = null
  tagForm.tagName = ''
  tagForm.description = ''
}

// 分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchTagList()
}

// 组件挂载时获取标签列表
onMounted(() => {
  fetchTagList()
})
</script>

<style scoped>
.search-add-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
</style>
